package com.zxl.manager.interceptor;

import com.zxl.manager.entity.User;
import com.zxl.manager.exception.SessionTimeoutException;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jimmy on 2017/8/11.
 */
public class SessionTimeoutInterceptor implements HandlerInterceptor {

    private List<String> allowUrls = new ArrayList<String>();
    public List<String> getAllowUrls() {
        return allowUrls;
    }
    public void setAllowUrls(List<String> allowUrls) {
        this.allowUrls = allowUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestUrl = httpServletRequest.getRequestURI();
        System.out.println(requestUrl+":aaaaa");
        for(String url : allowUrls) {
            if(requestUrl.endsWith(url)) {
                return true;
            }
        }
        HttpSession session = httpServletRequest.getSession();
        System.out.println(session.getId());
        User user = (User) session.getAttribute("userInfo");
        if(user == null || "".equals(user)) {
            httpServletResponse.setStatus(100);
            throw new SessionTimeoutException();
        } else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
